package com.xj.zookeeper.client;

import org.apache.zookeeper.AsyncCallback.ChildrenCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class AbstractZooKeeper implements Watcher,ChildrenCallback {
	private static final int SESSION_TIME = 2000;
	protected CountDownLatch countDownLatch = new CountDownLatch(1);
	protected ZooKeeper zooKeeper;

	@Override
	public void process(WatchedEvent event) {
		if (event.getState()== KeeperState.SyncConnected) {
			System.out.println("++++++++开始回调+++++++++++");
			countDownLatch.countDown();
		}
		/*try {
			zooKeeper.getChildren("/root", this, null);
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}*/
		System.out.println(event.getState()+"===========");
	}

	public void connect(String hosts) throws IOException, InterruptedException {
		zooKeeper = new ZooKeeper(hosts, SESSION_TIME, this);
		String auth_type = "digest";  
		String auth = "joey:some";  
		zooKeeper.addAuthInfo(auth_type, auth.getBytes());
		countDownLatch.await();
	}

	public void close() throws InterruptedException {
		zooKeeper.close();
	}

	@Override
	public void processResult(int rc, String path, Object ctx,List<String> children) {
		System.out.println(children.size()+"==00==");
	}

}
